package cn.onlineclass.servlet;

import cn.onlineclass.common.*;
import cn.onlineclass.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//login.do
//updatesubject.do
//delgrade.do
@WebServlet("*.do")//servlet的通配符
public class MainServlet extends HttpServlet {

    private UnitController unit =new UnitController();
    private MajorController major =new MajorController();
    private RescourceController rescource =new RescourceController();
    private VisitController visit =new VisitController();
    private CollectController collect =new CollectController();
    private CommentController comment =new CommentController();
    private UserController user =new UserController();
    private BookConntroller book =new BookConntroller();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    //  grade-add
    //grade-del
    //组合请求访问地址:类的属性名-方法名
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String path = request.getServletPath();
        path = path.substring(1, path.length() - 3);
        //path其实就是方法名，参数是可预期的
        String ar[] = path.split("-");
        if (ar.length == 2) {
            try {
                String field = ar[0];
                String methodName = ar[1];
                Field f = this.getClass().getDeclaredField(field);
                f.setAccessible(true);
                Object controller = f.get(this);//??? main.subject   main.grade
                Method m2 = controller.getClass().getDeclaredMethod(methodName, HttpServletResponse.class, HttpServletRequest.class);
                Object rtn = m2.invoke(controller, response, request);

                if (rtn instanceof String) {
                    if (StringUtil.isBlank(rtn))
                        return;
                    String location = (String) rtn;
                    if (location.startsWith("redirect:")) {
                        response.sendRedirect(location.substring(9));
                        return;
                    }
                    request.getRequestDispatcher((String) rtn).forward(request, response);
                    return;
                }
                if(rtn!=null){
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().print(JSON.toJSONStringWithDateFormat(rtn, "yyyy-MM-dd", SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNonStringValueAsString));
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(501, "方法没有找到！");
            }
        } else {
            try {
                Method method = this.getClass().getDeclaredMethod(path, HttpServletResponse.class, HttpServletRequest.class);
                Object rtn = method.invoke(this, response, request);
                if (rtn instanceof String) {
                    if (StringUtil.isBlank(rtn))
                        return;
                    String location = (String) rtn;
                    if (location.startsWith("redirect:")) {
                        response.sendRedirect(location.substring(9));
                        return;
                    }
                    request.getRequestDispatcher((String) rtn).forward(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                response.sendError(501, "方法没有找到！");
            }
        }
//        String path=request.getServletPath();
//        path= path.substring(1,path.length()-3);
//        //path其实就是方法名，参数是可预期的
//        try {
//            Method method=this.getClass().getDeclaredMethod(path,HttpServletResponse.class,HttpServletRequest.class);
//            Object rtn=method.invoke(this,response,request);
//            if(rtn instanceof String){
//                if(StringUtil.isBlank(rtn))
//                    return;
//                String location=(String)rtn;
//                if(location.startsWith("redirect:")){
//                    response.sendRedirect(location.substring(9));
//                    return;
//                }
//                request.getRequestDispatcher((String)rtn).forward(request,response);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.sendError(501,"方法没有找到！");
//        }


//        response.setContentType("text/html;charset=utf-8");
//        PrintWriter out = response.getWriter();
//        out.print("<html>");
//        out.print("<body>");
//        out.print("<h1>");
//        out.print("contextpath:"+request.getContextPath());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("url:"+request.getRequestURL());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("URI:"+request.getRequestURI());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("servlet path:"+request.getServletPath());
//        out.print("</h1>");
//        out.print("<h1>");
//        out.print("server:"+request.getScheme()+":"+request.getServerName()+":"+request.getServerPort());
//        out.print("</h1>");
//        String path=request.getServletPath();
//        path= path.substring(1,path.length()-3);
//        if(path.equals("login")){
//            out.print("这是一个登录操作");
//            String location=login(response,request);
//            if(!StringUtil.isBlank(location))
//                request.getRequestDispatcher(location).forward(request,response);
//        }else if(path.equals("delsubject")){
//            out.print("这是一个删除课程操作");
//        }else if(path.equals("updatesubject")){
//            out.print("这是一个更新课程操作");
//        }else{
//            out.print("未知操作");
//        }

        //  out.print("</body>");
        // out.print("</html>");
    }

    //参数还是request和Response，返回的值表示视图的地址
    public String login(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {
        String name = request.getParameter("userName");
        String pass = request.getParameter("userPass");
        //Ad
        if (name.startsWith("java76") && pass.equals("123")) {
            request.getSession().setAttribute("USER_LOGIN", name);
            return "redirect:main.jsp";
        }
        request.setAttribute("msg", "错误的用户名或者密码！");
        return "login.jsp";
    }
}
